/*
* 客户按项目销售明细
*/
public without sharing class AssignmentSaleDetailController {

	public String accpk ;//客户的pk

	public Boolean isErr {get;set;}

    public Boolean isSeeAll {get;private set;}

	public User u ;//当前用户

	public String sql {get; private set;}

	public Integer  productCounts {get;private set;}

	public String whereStr {get;set;}

	public String productJson {get;set;}

	public String company ;

    public String secret ;

    public AssignmentSaleDetailController() {
        accpk = System.currentPageReference().getParameters().get('accpk');
        secret = System.currentPageReference().getParameters().get('secret');
        sql = '';
        whereStr = '';
        productCounts = 0;
        productJson = '{}';
    }

	public void init(){
    	//0.获取当前用户信息
    	u = [select Id,Name,SubCompany__c,Profile.Name from User where Id=:UserInfo.getUserId()];
 		Map<String,String >   companyMap = ImportObject.getPicklistValues('Contract__c','Corpcode__c',false);
 		company = companyMap.get(u.SubCompany__c);


        if(secret == null)setError('页面打开错误!');
        if( secret != null && secret != EncodingUtil.base64Encode(Crypto.generateDigest('MD5',Blob.valueOf(u.Id+'secret'))))setError('没有权限!');
    	//1.参数不能为空
    	if(accpk == null){
            setError('页面打开错误!');
            return;
        }
        accpk = EncodingUtil.base64Decode(accpk).toString();
    	isSeeAll = getAllRigth();
       	setSql(company,accpk);
    	//2.验证当前用户是否有权限查看这些数据
    	if(!isSeeAll){
    		if(!isHasRight(accpk))setError('没有权限查看!');
    	}
    	getProductCount();

    }
    //将参数置空
    public void setNil(){
    	whereStr ='';
    	productJson = '{}';
    }
    //获取当前的产品条数
    public void getProductCount(){
    	
    	String  psql = ' select ProductPK__c,Product__r.Name  from AssignmentSaleDetail__c where AccountPK__c =\''+accpk+'\' ';
    	
    	 if(!isSeeAll) {
    	 	psql += ' and  CompanyCode__c = \''+company+ '\'';
    	 }

    	if(whereStr.length() > 0)psql +=  whereStr;


    	psql += ' Group by ProductPK__c ,Product__r.Name  ';
    	List<AggregateResult> prds = Database.query(psql);
    	productCounts = prds.size();
    	Map<String,String> pdMap = new Map<String,String>();

    	for (AggregateResult arg : prds ) {
    		Object  key = arg.get('ProductPK__c');
    		Object name = arg.get('Name') == null ?  key: arg.get('Name') ;
    		pdMap.put(String.valueOf(key), String.valueOf(name));
    	}

    	productJson = EncodingUtil.urlEncode(JSON.serialize(pdMap), 'UTF-8'); 


    }
    //设置查询语句
    public void setSql(String com , String accpkt){
    	if(com == null)setError('子公司信息维护错误!请联系管理员');
    	sql = ' select Id,ProductPK__c,AccountPK__c,Account__r.Name ,Product__r.Name,Category1__c,  ';
    	sql += ' Category2__c,Brand__c, Year__c,Month__c,SaleAmount__c ,Product__r.NCCode__c,Product__r.Spec__c ,Product__r.SerialNo__c ';
    	sql += ' from AssignmentSaleDetail__c where AccountPK__c = \''+accpkt+'\' ';
    	if(isSeeAll)return;
    	sql += ' and  CompanyCode__c = \''+com+'\'';

    }
    //是否有所有数据查看权限
    public Boolean getAllRigth(){
        String right =Label.AssignmentAllRight;

        if(right != null){
            for(String r : right.split(',',-1)){
                if(r == u.Profile.Name) return true;
                if(r == u.Name) return true;
            }
        }
        return false;
    }
    ///是否有当前客户的数据查看权限
    public Boolean isHasRight(String accpkt ){

    	//1.找到客户的所有人和所有人的经理/主管
    	Account acc = [select Id ,OwnerId,Owner.ManagerId from Account where NCICCode__c =:accpkt];
    	if(acc == null) return false;
    	Set<Id> saleset = new Set<Id>();
    	saleset.add(acc.OwnerId);
    	if(acc.Owner.ManagerId != null )saleset.add(acc.Owner.ManagerId);
    	//2.找到协同小组中包含当前用户的客户
    	for(AccountTeamMember at : [select Id ,UserId,User.ManagerId  from AccountTeamMember where Account.NCICCode__c  =:accpkt and teammemberrole = '同客户多人负责']){
    		if(at.User.ManagerId != null )saleset.add(at.User.ManagerId);
    		if(at.UserId != null )saleset.add(at.UserId);

    	}
    	if(saleset.contains(u.Id))return true;
    	return false;

    }
    public void setError(String message){
    	isErr = true;
    	ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,message));
    }


}